package com.newlink.building.common_base.utils

import android.text.InputFilter
import android.text.Spanned
import android.text.TextUtils
import java.util.regex.Pattern

class MaxValueFilter(private val max: Int = 10000) : InputFilter {
    //    private val pattern = Pattern.compile("^([1-9]\\d{0,3}|10000)$|^0$")
    private val pattern: Pattern

    init {
        pattern = generatePattern(max)
    }

    private fun generatePattern(max: Int): Pattern {
        val maxStr = max.toString()
        val maxLength = maxStr.length
        var regex = "^0$"

        if (max > 0) {
            // 处理小于最大长度的数字
            if (maxLength > 1) {
                regex += "|^[1-9]\\d{0,${maxLength - 2}}$"
            }

            // 处理最大长度且小于最大值的数字
            var prefix = ""
            for (i in 0 until maxLength - 1) {
                val digit = maxStr[i]
                if (digit > '0') {
                    val start = if (i == 0) 1 else 0
                    for (j in start until digit.digitToInt()) {
                        regex += "|^${prefix}${j}\\d{${maxLength - i - 1}}$"
                    }
                }
                prefix += digit
            }

            // 包含最大值本身
            regex += "|^$max$"
        }

        return Pattern.compile(regex)
    }

    override fun filter(
        source: CharSequence,
        start: Int,
        end: Int,
        dest: Spanned,
        dstart: Int,
        dend: Int,
    ): CharSequence? {
        val input =
            dest.subSequence(0, dstart).toString() + source.subSequence(start, end)
                .toString() + dest.subSequence(
                dend,
                dest.length
            ).toString()
        return if (TextUtils.isEmpty(input) || pattern.matcher(input).matches()) {
            null
        } else {
            ""
        }
    }
}